#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
#define SIZE 1024
#define TYPE "[%s@%s %s]# "
#define MAXARGC 128
char* my_argv[MAXARGC];
int my_argc = 0;
const char* GetUserName() {
    const char* UserName = getenv("USER");
    return UserName == NULL ? "none" : UserName;
}
const char* GetHostName() {
    const char* HostName = getenv("HOSTNAME");
    return HostName == NULL ? "none" : HostName;
}
const char* GetPwd() {
    const char* Pwd = getenv("PWD");
    return Pwd == NULL ? "none" : Pwd;
}
void MakeCommendLine(char commend_temp[], int size) {
    snprintf(commend_temp, size, TYPE, GetUserName(), GetHostName(), GetPwd());
}
void PrintCommendPrompt() {
    char Commend[1024];
    MakeCommendLine(Commend, sizeof(Commend));
    printf("%s", Commend);
    fflush(stdout);
}
bool GetCommendLine(char* line, int size) {
    char* temp = fgets(line, size, stdin);
    if(temp == NULL) {
        return false;
    }
    line[strlen(temp) - 1] = '\0'; // 清空我们的'\n'
    if(strlen(temp) == 0) return false;
    return true;
}
void CommendAnalyse(char* commendline) {
    #define seq " "
    my_argv[my_argc++] = strtok(commendline, seq);
    while((my_argv[my_argc++] = strtok(NULL, seq)) != NULL) 
    my_argc--;
}
void Execute() {
    pid_t id = fork();
    if(id == 0) // 子进程
    {
        execvp(my_argv[0], my_argv);
        exit(1);
    }
    // 父进程
    pid_t temp = waitpid(id, nullptr, 0);
    (void)temp;
}
int main() {
    while(1) {
        // 输出命令行提示符
        PrintCommendPrompt();

        // 获取输入命令
        char commendline[SIZE];
        if(!GetCommendLine(commendline, sizeof(commendline))) {
            continue;
        }

        // 命令行分析
        CommendAnalyse(commendline);

        // 执行命令
        Execute();
    }
    return 0;
}